'''
@author: haiwen
@date: 2020/9/28
@file: base.py
'''
#创建BasePage--保存页面操作的公共方法
from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from pylib.pulgins import Config
from conf.env import iwait,timeout

class WebdriverCreater:
    def __new__(cls, *args, **kwargs):
        #单例模式-判断当前类是否有实例，有就返回该实例，没有就创建再返回
        if not hasattr(cls,'_instance'):
            cls._instance = object.__new__(cls)
        return cls._instance

    def get_driver(self):
        #先判断的当前对象有没有driver属性
        if not hasattr(self,'driver'):
            self.driver = webdriver.Chrome()  #如果没有直接赋值
            self.driver.implicitly_wait(iwait)
            self.driver.set_page_load_timeout(timeout) #页面加载超时时间
            self.driver.set_scrript_timeout(timeout) #JS超时时间
        return self.driver

class BasePage:
    def __init__(self):
        self._init_eles()
        #初始化driver-始终只有一个对象
        if not hasattr(self,'__driver'):
            self.__driver=WebdriverCreater().get_driver()

    def _init_eles(self):
        # 读取配置文件中的元素定位方法
        class_names = [m.__name__ for m in self.__class__.mro()][:-2]  #去掉basepage和object

        for name in class_names:
            conf = Config.read_yml('conf/locators.yml')[name]
            # 将元素定位方法赋值给对象属性
            for key in conf:
                self.__setattr__(key, conf[key])


    def click(self,locators):
        ele=WebDriverWait(self.__driver,iwait).until(EC.element_to_be_clickable((locators[0],locators[1])))
        ele.click()

    def input_text(self,text,locators):
        self.__driver.find_element(*locators).send_keys(text)

    def to_url(self,url):
        self.__driver.get(url)

    def click_multi(self,locators):
        eles=self.__driver.find_elements(*locators)
        for ele in eles:
            ele.click()

    def select_target(self,target,locators):
        eles = self.__driver.find_elements(*locators)
        #遍历候选目标，根据特征选择
        for ele in eles:
            #根据元素文本判断
            if ele.text == target:
                ele.click()
                return True  #代表选择成功
        return False  #表示没有选择到目标

    def eles_text(self,locators):
        eles = self.__driver.find_elements(*locators)
        return [ele.text for ele in eles]

    def close_browser(self):
        self.__driver.quit()
        self.__driver=None


